package com.caow.baselibrary

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.caow.baselibrary.widget.LoadingDialog
import java.lang.reflect.ParameterizedType

/**
 * @Author caow
 * 2023/6/30
 */
abstract class BaseFragment<viewDataBinging : ViewDataBinding, VM : BaseViewModel> : Fragment() {


    protected val TAG by lazy { javaClass.simpleName }

    protected lateinit var binding: viewDataBinging
    protected val viewModel: VM by lazy {
        val entityClass: Class<VM> =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VM>
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)
        ).get(entityClass)
    }

    abstract fun initLayoutId(): Int
    abstract fun initViewModelId(): Int

    // 加载中弹窗
    private val loadingDialog by lazy { LoadingDialog(requireActivity()) }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
//        val view = inflater
//            .inflate(initLayoutId(), container, false)
//        Log.i("caow", "view ====== $view")
        binding = DataBindingUtil.inflate(inflater, initLayoutId(), container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.setVariable(initViewModelId(), viewModel)
        lifecycle.addObserver(viewModel)
        initLoadingDialog()
    }

    private fun initLoadingDialog() {
        viewModel.showLoadingDialog.observe(this, Observer { loadingDialog.show() })
        viewModel.dismissLoadingDialog.observe(this, Observer { loadingDialog.dismiss() })
    }
}